/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session.stateless;

import entity.BranchAddressEntity;
import entity.IndustryTypeEntity;
import entity.StakeholderEntity;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
//import util.entityHelper.StakeholderAccountState;
//import util.entityhelper.StakeholderAccountState;
import exception.ExistException;

/**
 *
 * @author Amelia
 */
@Stateless
@LocalBean
public class StakeholderSessionBean {

    @PersistenceContext
    private EntityManager entityManager;
  //  private StakeholderAccountState stakeholderAccountState;

    //register a new stakeholder
    public void addNewStakeholder(StakeholderEntity stakeholderTemp, BranchAddressEntity addressTemp, IndustryTypeEntity industryType) throws
            ExistException {
        if (checkUsernameExist(stakeholderTemp.getUsername())) {
            throw new ExistException("The username " + stakeholderTemp.getUsername() + " has already existed.");
        }

        if (checkEmailExist(stakeholderTemp.getCorpEmail())) {
            throw new ExistException("The email " + stakeholderTemp.getCorpEmail() + " has already existed.");
        }
        if (checkBizRegNumberExist(stakeholderTemp.getBizRegNumber())) {
            throw new ExistException("The business registration number " + stakeholderTemp.getBizRegNumber() + " has already existed.");
        }
        BranchAddressEntity address = new BranchAddressEntity(addressTemp);
        entityManager.persist(address);

        StakeholderEntity stakeholder = new StakeholderEntity(stakeholderTemp);
        stakeholder.setAddress(address);
        stakeholder.setStakeholderDesc("Please enter a short description of your business. This will appear in the portal");
        entityManager.persist(stakeholder);

        stakeholder.setIndustryType(industryType);
        industryType.getStakeholder().add(stakeholder);
        entityManager.merge(industryType);
    }

    public List<StakeholderEntity> getAllStakeholders() {
        Query query = entityManager.createQuery("SELECT s FROM Stakeholder s");
        return query.getResultList();
    }

    public void editStakeholderInfo(StakeholderEntity stakeholder) {
        entityManager.merge(stakeholder);
    }

    private boolean checkUsernameExist(String username) {
        Query query = entityManager.createQuery("SELECT s FROM Stakeholder s WHERE s.username = :username");
        query.setParameter("username", username);
        List list = query.getResultList();

        if (list.isEmpty()) {
            return false;
        }

        return true;
    }

    private boolean checkEmailExist(String email) {
        Query query = entityManager.createQuery("SELECT s FROM Stakeholder s WHERE s.corpEmail = :email");
        query.setParameter("email", email);
        List list = query.getResultList();

        if (list.isEmpty()) {
            return false;
        }

        return true;
    }

    private boolean checkBizRegNumberExist(String bizRegNumber) {
        Query query = entityManager.createQuery("SELECT s FROM Stakeholder s WHERE s.bizRegNumber = :bizRegNumber");
        query.setParameter("bizRegNumber", bizRegNumber);
        List list = query.getResultList();

        if (list.isEmpty()) {
            return false;
        }

        return true;
    }

    public StakeholderEntity retrieveStakeholderInfoByUsername(String username) {
        Query query = entityManager.createQuery("SELECT s FROM Stakeholder s WHERE s.username = :username");
        query.setParameter("username", username);
        return (StakeholderEntity) query.getSingleResult();
    }

    public List<IndustryTypeEntity> getIndustryTypeList() {
        System.out.println("Retrieving Industry Type Information...");
        Query query = entityManager.createQuery("SELECT i FROM IndustryTypeEntity i");

        return query.getResultList();
    }

/*    public StakeholderAccountState getStakeholderPortalInfoById(long stakeholderId)
            throws ExistException {
       

        Query q = entityManager.createQuery("SELECT s FROM Stakeholder s WHERE s.id = :accId");
        q.setParameter("accId", stakeholderId);

        if (q.getResultList().isEmpty()) {
            // might have to move this elsewhere....
            // EXCEPTION
            throw new ExistException("SOMETHING IS WRONG; Please Login again");

        } else {
            //System.out.println("Stakeholder exist");
            StakeholderEntity stakeholder = (StakeholderEntity) q.getSingleResult();
            setStakeholderAccountState(new StakeholderAccountState(stakeholder.getStakeholderId(),
                    stakeholder.getUsername(),
                    stakeholder.getStakeholderDesc(),
                    stakeholder.getImgUrl()));
        }

        return stakeholderAccountState;
    }
    

    public StakeholderAccountState getStakeholderByUsername(String stakeholderUsername) throws ExistException {
        //StakeholderAccountState stakeholderAccountState = null;
        //System.out.println("userName at backend: " +stakeholderUsername.trim());

        // find account id
        Query q = entityManager.createQuery("SELECT s FROM Stakeholder s WHERE s.username = :accName");
        q.setParameter("accName", stakeholderUsername.trim());

        if (q.getResultList().isEmpty()) {
            // EXCEPTION
            throw new ExistException("TOURIST_ACCT_DOES_NOT_EXIST");

        } else {
            System.out.println("Stakeholder exist");
            StakeholderEntity stakeholder = (StakeholderEntity) q.getSingleResult();
            setStakeholderAccountState(new StakeholderAccountState(
                    stakeholder.getStakeholderId(),
                    stakeholder.getUsername(),
                    stakeholder.getPassword(),
                    stakeholder.getActivate()));


        }
        return getStakeholderAccountState();
    }//end of method getStakeholder by ID

    
    
    public boolean addPortalInfoByInfo(StakeholderAccountState stakeholderAcc) throws ExistException {
        boolean success = false;

        StakeholderEntity stakeholder = entityManager.find(StakeholderEntity.class, stakeholderAcc.getId());
        if (stakeholder == null) {

            return false;
        }
        System.out.println("Stakeholder Desc at backend: "+ stakeholderAcc.getStakeholderDesc());
        stakeholder.setStakeholderDesc(stakeholderAcc.getStakeholderDesc());
        stakeholder.setImgUrl(stakeholderAcc.getImgUrl());
        success = true;

        return success;
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    /**
     * @return the stakeholderAccountState
     */
 /*   public StakeholderAccountState getStakeholderAccountState() {
        return stakeholderAccountState;
    }

    /**
     * @param stakeholderAccountState the stakeholderAccountState to set
     */
   /* public void setStakeholderAccountState(StakeholderAccountState stakeholderAccountState) {
        this.stakeholderAccountState = stakeholderAccountState;
    }*/
    
    /*
    //for putting data into the web pages
    public List<Industry> getIndustry() {
    Query query = entityManager.createQuery("SELECT r FROM Industry r");
    return query.getResultList();
    }
    
    public List<IndustryType> getIndustryTypes(Industry industry) {
    if (industry != null) {
    Query query = entityManager.createQuery("SELECT it FROM IndustryType it where it.industry =:industry");
    query.setParameter("industry", industry);
    return query.getResultList();
    }
    return null;
    }
    
    //reteriving based on industry name
    public List<IndustryInfoType> getIndustryInfoTypes(String industryName) {
    if (industryName != null) {
    //select industry where industry name is the same
    Query q = entityManager.createQuery("SELECT i FROM Industry i where i.industryName =:industryName");
    q.setParameter("industryName", industryName);
    List<Industry> industryResult = q.getResultList();
    
    for (int a = 0; a < industryResult.size(); a++) {
    //select industry type table where industryType_industry is the same as above selected industry
    List<IndustryType> result = getIndustryTypes(industryResult.get(a));
    //select industry info type table where industryInfoType_industryType is the same as above selected industryType
    String queryString = "SELECT i FROM IndustryInfoType i where i.industryType =:";
    for (int e = 0; e < result.size(); e++) {
    if (e == result.size() - 1) {
    queryString += "s" + e;
    } else {
    queryString += "s" + e + " OR i.industryType =:";
    }
    }
    Query query = entityManager.createQuery(queryString);
    for (int i = 0; i < result.size(); i++) {
    query.setParameter("s" + i, result.get(i));
    }
    return query.getResultList();
    }
    }
    return null;
    }
    
    //reteriving based on industry
    public List<IndustryInfoType> getIndustryInfoTypes(Industry industry) {
    if (industry != null) {
    List<IndustryType> result = getIndustryTypes(industry);
    String queryString = "SELECT i FROM IndustryInfoType i where i.industryType =:";
    for (int i = 0; i < result.size(); i++) {
    if (i == result.size() - 1) {
    queryString += "s" + i;
    } else {
    queryString += "s" + i + " OR i.industryType =:";
    }
    }
    Query query = entityManager.createQuery(queryString);
    for (int i = 0; i < result.size(); i++) {
    query.setParameter("s" + i, result.get(i));
    }
    return query.getResultList();
    }
    return null;
    }
    
    //reteriving only 1 industry type - selection = "single"
    public List<IndustryInfoType> getIndustryInfoTypes(IndustryType IndustryType) {
    if (IndustryType != null) {
    Query query = entityManager.createQuery("SELECT i FROM IndustryInfoType i where i.industryType =:IndustryType ");
    query.setParameter("IndustryType", IndustryType);
    return query.getResultList();
    }
    return null;
    }
    
    //for reteriving array (selection = "multiple")- error when loading list onto jsf page
    public List<IndustryInfoType> getIndustryInfoTypes(IndustryType[] IndustryType) {
    List list = new ArrayList();
    if (IndustryType != null) {
    for (int i = 0; i < IndustryType.length; i++) {
    Query query = entityManager.createQuery("SELECT i FROM IndustryInfoType i where i.industryType =:IndustryType ");
    query.setParameter("IndustryType", IndustryType[i]);
    list.add(query.getResultList());
    }
    }
    return list;
    }
     */
    
}
